package com.apps.ftapp.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.apps.ftapp.R;
import com.apps.ftapp.bean.All;
import com.apps.ftapp.bean.ExamOption;
import com.apps.ftapp.bean.ExamQuestion;
import com.apps.ftapp.bean.Personal;
import com.apps.ftapp.bean.QuestionEntry;
import com.apps.ftapp.fragment.ExamMaterialFragment;
import com.apps.ftapp.fragment.ExamMultiSelectFragment;
import com.apps.ftapp.fragment.ExamRadioFragment;
import com.apps.ftapp.model.TjCtModel;
import com.apps.ftapp.ui.IExamResponseListener;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.StatusBarUtils;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;

/**
 * 我的错题
 */
public class MyErrorDetailActivity extends FragmentActivity implements IExamResponseListener, View.OnClickListener {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.txt_timer)
    TextView txtTimer;
    @BindView(R.id.fenxiang)
    ImageView fenxiang;
    @BindView(R.id.shoucang)
    ImageView shoucang;
    @BindView(R.id.timu)
    ImageView timu;
    @BindView(R.id.gengduo)
    RelativeLayout gengduo;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;

    final Gson gson = new Gson();
    private String id;

    private String questionID;//当前题目ID

    com.apps.ftapp.db.Singleton singleton = com.apps.ftapp.db.Singleton.getInstance();

    private List<ExamQuestion> mQuestion = new ArrayList<>();

    ViewPagerAdapter mViewPagerAdapter;

    private TjCtModel result;

    private int current = 0;


    private String lmname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_error_detail);
        ButterKnife.bind(this);

        // 初始化ShareSDK（不可缺失）
        ShareSDK.initSDK(this);

        StatusBarUtil.setColor(MyErrorDetailActivity.this, Color.WHITE, 1);
        StatusBarUtils.StatusBarLightMode(this);

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        id = bundle.getString("id");
//        initView();
        L.i("main", "-------------------------------------" + id);
        loadData(id);

//        Timer timer = new Timer(txtTimer);
//        timer.start(txtTimer);

        imgBack.setOnClickListener(this);
        shoucang.setOnClickListener(this);
        timu.setOnClickListener(this);
        timu.setVisibility(View.GONE);
        txtTimer.setVisibility(View.GONE);
        shoucang.setVisibility(View.GONE);

        fenxiang.setOnClickListener(this);
    }


    private void initView() {

        collectQuestion(mQuestion.get(current).getCollection() == 1);

        mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mQuestion);
        mViewPager.setAdapter(mViewPagerAdapter);

//        ViewPagerUtils.setSliderTransformDuration(mViewPager, 300, new DecelerateInterpolator());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == mQuestion.size()) {
                    mViewPagerAdapter.notifyDataSetChanged();
                } else {
                    //更新收藏状态
                    collectQuestion(mQuestion.get(position).getCollection() == 1);
                }
                current = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

//        关掉 右划 返回
//        disableSlideBack();
//
//        Arad.bus.register(this);
    }


    public void collectQuestion(boolean fill) {
        if (fill) {
            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_2));
        } else {
            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_1));
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.shoucang:

                sc();
                break;

            case R.id.timu:
                ActivitySkipUtil.skipAnotherActivity(MyErrorDetailActivity.this, MyStSucActivity.class, false);
                break;

            case R.id.fenxiang:
                share();
                break;

        }
    }


    /**
     * 收藏
     */
    private void sc() {
        //判断是否收藏
        //
        L.i("main", mQuestion.get(current).getCollection() + "kljkj>>>>>>" + current + ">>>>" + mQuestion.get(current).getStem());
        if (0 == mQuestion.get(current).getCollection()) {
            L.i("main", "收藏。。。");
            RequestParams params = new RequestParams();
            params.put("token", Constant.token);
            params.put("userId", Constant.uid);
            params.put("question_id", result.getItem().getQuestionId());
            params.put("targetType", "testpaper");
            params.put("targetId", id);
            Async.post("question/favorite", params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    if (statusCode == 200) {
                        L.i("main", new String(responseBody));
                        try {
                            //请求成功
                            Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                            L.i("main", jsonBean.toString());
                            if (1 == Tools.isDoubleNull(jsonBean.get("success")) || 1.0 == Tools.isDoubleNull(jsonBean.get("success"))) {
                                Toasty.normal(getApplicationContext(), "收藏成功").show();
//                            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_2));
//                            result.getData().get(cur).setFavorite("1");
                                mQuestion.get(current).setCollection(1);
                                L.i("main", ">>>" + current);
                                collectQuestion(mQuestion.get(current).getCollection() == 1);
                            } else {
//                            mQuestion.get(cur).setCollection(0);
                                Toasty.normal(getApplicationContext(), Tools.isNull(jsonBean.get("error"))).show();
                            }
                        } catch (Exception e) {
                        }
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                }
            });
        } else {

            //取消收藏

            L.i("main", "取消收藏。。。");
            RequestParams params = new RequestParams();
            params.put("token", Constant.token);
            params.put("userId", Constant.uid);
            params.put("question_id", result.getItem().getQuestionId());
            params.put("targetType", "testpaper");
            params.put("targetId", id);
            Async.post("question/unfavorite", params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    if (statusCode == 200) {
                        L.i("main", new String(responseBody));
                        try {
                            //请求成功
                            Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                            L.i("main", jsonBean.toString());
                            if (1 == Tools.isDoubleNull(jsonBean.get("success")) || 1.0 == Tools.isDoubleNull(jsonBean.get("success"))) {
                                Toasty.normal(getApplicationContext(), "取消收藏").show();
//                            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_2));
//                            result.getData().get(cur).setFavorite("1");
                                mQuestion.get(current).setCollection(0);
                                L.i("main", ">>>" + current);
                                collectQuestion(mQuestion.get(current).getCollection() == 1);
                            } else {
//                            mQuestion.get(cur).setCollection(0);
                                Toasty.normal(getApplicationContext(), Tools.isNull(jsonBean.get("error"))).show();
                            }
                        } catch (Exception e) {
                        }
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                }
            });

        }


    }


    /**
     * Viewpager 内容
     */
    private class ViewPagerAdapter extends FragmentStatePagerAdapter {

        List<ExamQuestion> mQuestionList;

        ViewPagerAdapter(FragmentManager fm, List<ExamQuestion> questionList) {
            super(fm);
            mQuestionList = questionList;
//            L.i("main",".,.,.,.,.,.,.,.,.,.,.,.,.,."+questionList.toString());
        }

        @Override
        public Fragment getItem(int position) {
            if (position == mQuestionList.size()) {
                //结束
//                return ExamPreviewFragment.newInstance(mTitle, mPresenter.getAnswerRecordJson(), mPresenter.getSeconds(), type);
            }
            ExamQuestion question = mQuestionList.get(position);

//            L.i("main",".,.,.,.,.,.,.,.,.,.,.,.,.,.");

            QuestionEntry entry = new QuestionEntry();
            entry.setExamQuestion(question);
            entry.setPosition(position);
            entry.setTitle(Tools.getType(question.getType()));
            entry.setCount(mQuestionList.size());
            entry.setExam_or_analysis(1);
            entry.setLmname(lmname);


            L.i("main", "question.getType()<<<<<" + question.getType());
            switch (question.getType()) {
                case 0://单选题
//                    timu.setVisibility(View.VISIBLE);
                    return ExamRadioFragment.newInstance(entry, true);
                case 1://多选题
//                    timu.setVisibility(View.VISIBLE);
                    return ExamMultiSelectFragment.newInstance(entry);
                case 2://不定项选择题
//                    timu.setVisibility(View.VISIBLE);
                    return ExamMultiSelectFragment.newInstance(entry);
                //TODO 3
                case 3://填空题
//                    timu.setVisibility(View.GONE);
                    return ExamMaterialFragment.newInstance(entry);
                case 4://判断题
//                    timu.setVisibility(View.VISIBLE);
                    return ExamRadioFragment.newInstance(entry, true);
                case 5://问题题
//                    timu.setVisibility(View.GONE);
                    return ExamMaterialFragment.newInstance(entry);
                case 6://材料题
//                    timu.setVisibility(View.GONE);
                    return ExamMaterialFragment.newInstance(entry);
            }

            return ExamRadioFragment.newInstance(entry, true);
        }

        @Override
        public int getItemPosition(Object object) {
//            if (object instanceof ExamPreviewFragment) {
//                return POSITION_NONE;
//            }
            return super.getItemPosition(object);
        }

        @Override
        public int getCount() {
            return (mQuestionList == null || mQuestionList.size() == 0) ? 0 : mQuestionList.size();
        }
    }


    @Override
    public void onRadio(String selectedId, int whichOne) {
        L.i(selectedId + ":我是第" + whichOne + "个题");
        ExamQuestion question = mQuestion.get(whichOne);
        boolean isCorrect = false;
        for (ExamOption option : question.getDataList()) {
            if (option.getIs_correct() == 1) {
                if (option.getId().equals(selectedId)) {
                    isCorrect = true;
                    break;
                }
            }
        }
        com.apps.ftapp.db.Singleton.getInstance().updDatiList(whichOne + 1, true);


        Map m = new HashMap();
        m.put("id", question.getId());
        m.put("ans", whichOne + "");
        singleton.addData(m);

//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(selectedId);
//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(isCorrect ? 1 : 0);

        gotoNextPage(whichOne);
    }

    @Override
    public void onMutil(List<String> selectedID, int whichOne) {

        if (selectedID.size() > 0) {
            boolean isCorrect = true;
            String _ids = "";
            for (int i = 0; i < selectedID.size(); i++) {
                if (i != selectedID.size() - 1) {
                    _ids += selectedID.get(i) + ",";
                } else {
                    _ids += selectedID.get(i);
                }
            }

            ExamQuestion question = mQuestion.get(whichOne);
            for (ExamOption option : question.getDataList()) {
                if (option.getIs_correct() == 0) {
                    if (_ids.contains(option.getId())) {
                        isCorrect = false;
                        break;
                    }
                }
            }
//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(_ids);
//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(isCorrect ? 1 : 0);
        } else {
//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(null);
//            mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(2);
        }
    }


    /**
     * 执行下一个页面
     *
     * @param currentPosition 当前页
     */
    private void gotoNextPage(int currentPosition) {
        int nextPage = currentPosition + 1;
        if (nextPage < mQuestion.size() + 1) {
            mViewPager.setCurrentItem(nextPage, true);
        }
        if (nextPage == mQuestion.size()) {
            mViewPagerAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onJudge(String selectedId, int whichOne) {
        boolean isCorrect = false;
        ExamQuestion question = mQuestion.get(whichOne);

        for (ExamOption option : question.getDataList()) {
            if (option.getIs_correct() == 1) {
                if (option.getId().equals(selectedId)) {
                    isCorrect = true;
                    break;
                }
            }
        }

//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setAnswer(selectedId);
//        mPresenter.getAnswerRecordJson().getArdj().get(whichOne).setIsRealy(isCorrect ? 1 : 0);

        gotoNextPage(whichOne);
    }


    private void loadData(String id) {

        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("id", id);
        L.i("main", "token:::" + Constant.token + ":::" + Constant.uid + ":::" + id);
        Async.post("course/manage/question/preview", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));

//                    TjCtModel result = new TjCtModel();

                    try {
                        result = gson.fromJson(new String(responseBody), TjCtModel.class);

                    } catch (Exception e) {

                    }

//                    if (1 == Tools.isIntNull(result.getSuccess())) {
                    for (int i = 0; i < 1; i++) {
                        TjCtModel.ItemBean d = result.getItem();
                        if ("".equals(Tools.isNull(questionID))) {
                            //
                            questionID = d.getQuestionId();
                        }


                        ExamQuestion ques = new ExamQuestion();
                        ques.setId(d.getQuestion().getId());
                        ques.setStem(d.getQuestion().getStem());
                        ques.setType(Tools.getType(Tools.isNull(d.getQuestionType())));

                        ques.setqNo(0);
                        ques.setSource(0);
                        ques.setCollection(Tools.isIntNull(d.getFavorite()));
                        ques.setAnalysis(d.getQuestion().getAnalysis());
                        ques.setIsRealy(1);

                        int j = 0;
                        List<ExamOption> options = new ArrayList();
                        for (String str : d.getQuestion().getMetas().getChoices()) {
//                                String xuanzede = Tools.isNull(d.getQuestion().getAnswer().get(j));
                            //正确答案
                            List<String> sss = d.getQuestion().getAnswer();//Tools.isNull(d.getQuestion().getTestResult().getAnswer()).split(",");
                            ExamOption opt = new ExamOption();
                            opt.setId(j + "");
                            opt.setContent(str);
                            //正确答案
                            if (sss != null && sss.size() > 0) {
                                for (String s : sss) {
                                    if (s.contains(j + "")) {
                                        L.i("main", "正确为：：：" + s);
                                        opt.setIs_correct(1);
                                    }
                                }
                            }
                            options.add(opt);
                            //
                            j++;
                        }
                        ques.setDataList(options);

                        Personal personal = new Personal();
                        personal.setDo_count(d.getPersonal().getDo_count());
                        personal.setRight_count(d.getPersonal().getRight_count());
                        personal.setWrong_count(d.getPersonal().getWrong_count() + "");
                        ques.setPersonal(personal);

                        All all = new All();
                        all.setDo_count(d.getAll_data().getDo_count());
                        all.setEasy_wrong(d.getAll_data().getEasy_wrong());
                        all.setWrong_rate(d.getAll_data().getWrong_rate());

                        ques.setAll(all);

                        StringBuffer ssb = new StringBuffer();
//                            L.i("main","PPPPP"+d.getQuestion().getAnswer());
                        for (String de : d.getQuestion().getAnswer()) {
                            ssb.append(de + ",");
                        }
                        ques.setAnswer(ssb.toString());
                        ques.setZzzz(d.getAnswer_compare());
                        ques.setAnalysis(d.getQuestion().getAnalysis());

//ques.set/


                        mQuestion.add(ques);
                    }

                    lmname = result.getLmname();

                    L.i("main", "mQuestionmQuestionmQuestion>>>>>" + mQuestion.size());
//                            mViewPagerAdapter.notifyDataSetChanged();
                    initView();
//                        singleton.setStartTime(Tools.getTime());
//                        singleton.setId(result.getResults().getId());
                }

//                }else{
//
////
//                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    private void share() {
        TjCtModel.ItemBean.ShareBean shareBean = result.getItem().getShare();
        if (null != shareBean) {
            OnekeyShare oks = new OnekeyShare();
            oks.disableSSOWhenAuthorize();
            oks.setTitle(shareBean.getTitle());
            oks.setTitleUrl(shareBean.getUrl());
            oks.setText(shareBean.getTitle());
            oks.setImageUrl(shareBean.getImage());
            oks.setUrl(shareBean.getUrl());
            oks.setSite(shareBean.getTitle());
            oks.setSiteUrl(shareBean.getUrl());
            oks.show(MyErrorDetailActivity.this);
        }
    }


}
